这篇文章来自一个 sf 社区问题的思考
原理很简单
1 . 首先, 你注意一下 /config/app.php
里面
/*
|--------------------------------------------------------------------------
| Class Aliases
|--------------------------------------------------------------------------
|
| This array of class aliases will be registered when this application
| is started. However, feel free to register as many as you wish as
| the aliases are "lazy" loaded so they don't hinder performance.
|
*/
'aliases' => [
'Route' => Illuminate\Support\Facades\Route::class,
];
2 . 因为有 Facades
, 所以我们直接去看 Illuminate\Support\Facades\Route::class
这个类返回的内容
* @method static \Illuminate\Routing\Route get(string $uri, \Closure|array|string $action)
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor()
{
return 'router';
}
3 . 那就简单了, 直接去找注册为 router
的组件
发现是在 Illuminate/Routing/RoutingServiceProvider.php
/**
* Register the router instance.
*
* @return void
*/
protected function registerRouter()
{
$this->app->singleton('router', function ($app) {
return new Router($app['events'], $app);
});
}
4 . new Router()
看到了没, 很显然就会返回 Illuminate/Routing/Router.php
实例; 是不是发现了
/**
* Register a new GET route with the router.
*
* @param string $uri
* @param \Closure|array|string|null $action
* @return \Illuminate\Routing\Route
*/
public function get($uri, $action = null)
{
return $this->addRoute(['GET', 'HEAD'], $uri, $action);
}
(づ ̄3 ̄)づ╭❤~ 宣我 !! 么么
问答时间
1) . 我确认了 'router' 是在Illuminate/Routing/RoutingServiceProvider.php
里面的 ,
但是为什么没有配置在 /config/app.php
的 providers
里面呢
答案在这里
Illuminate/Foundation/Application.php
注意 base service providers
和 configured providers
/**
* Register all of the base service providers.
*
* @return void
*/
protected function registerBaseServiceProviders()
{
$this->register(new EventServiceProvider($this));
$this->register(new LogServiceProvider($this));
$this->register(new RoutingServiceProvider($this));
}
/**
* Register all of the configured providers.
*
* @return void
*/
public function registerConfiguredProviders()
{
(new ProviderRepository($this, new Filesystem, $this->getCachedServicesPath()))
->load($this->config['app.providers']);
}
2) . 那我看到在 /config/app.php
注册了一个看起来像路由相关的 App\Providers\RouteServiceProvider::class,
它是干嘛用的呢?
答案在这里
首先 App\Providers\RouteServiceProvider
继承自 Illuminate\Foundation\Support\Providers\RouteServiceProvider
; (并且调用了我们上面的 Illuminate\Support\Facades\Route
, 可以使用 Route::*
)
直接看看 Illuminate\Foundation\Support\Providers\RouteServiceProvider
你就会明白
public function boot()
{
$this->setRootControllerNamespace();
if ($this->app->routesAreCached()) {
$this->loadCachedRoutes();
} else {
$this->loadRoutes();
$this->app->booted(function () {
$this->app['router']->getRoutes()->refreshNameLookups();
$this->app['router']->getRoutes()->refreshActionLookups();
});
}
}
public function register()
{
// 没有在这里注册
}
boot 方法是在所有服务提供者都注册完成后调用的方法, 所以说 这是启动后 注册路由的 provider
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。